const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

const index = require('./routes/index');
const me = require('./routes/me');
const embed = require('./routes/embed');
const db = require('./libs/db');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

passport.use(new LocalStrategy(
  function (username, password, done) {
    db.userValidation(username, password).then(u => {
      if (u) {
        return done(null, {
          username: u.username,
          id: u._id
        });
      }
      return done(null, false);
    });
  }
));
passport.serializeUser(function (user, done) {
  done(null, user);
});

passport.deserializeUser(function (user, done) {
  done(null, user);
});

// required for passport session
// NOTE sessions will only available via runtime, restart node will causing sessions localhost
// to store sessions, should have a implemention to store sessions in mongodb
app.use(session({
  secret: 'jiepu_embed',
  resave: false,
  saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());


// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// node_modules
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));

app.use('/', index);
app.use('/me', me);
app.use('/embed', embed);

app.get('/login', function (req, res, next) {
  res.render('login');
});
app.post('/login', passport.authenticate('local', {
  successRedirect: '/me',
  failureRedirect: '/login'
}));


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;